<script setup lang="ts">
import {message} from "ant-design-vue";
import {
  CrowdLabelInterface,
  FindRecommendCrowdRecScene
} from "~/contentScripts/views/wxt/BatchAddingProducts/components/Crowd/CrowdInterface";
import CrowdTopicTemplatePanel
  from "~/contentScripts/views/wxt/BatchAddingProducts/components/Crowd/CrowdTopicTemplatePanel.vue";
import CustomCrowd from "~/contentScripts/views/wxt/BatchAddingProducts/components/Crowd/CustomCrowd.vue";
import FindRecommendCrowdPanel
  from "~/contentScripts/views/wxt/BatchAddingProducts/components/Crowd/findRecommendCrowdPanel.vue";
import AutoSearchKeywords from "~/contentScripts/views/wxt/components/AutoSearchKeywords.vue";
import CustomSearchKeywords from "~/contentScripts/views/wxt/components/CustomSearchKeywords.vue";
import {WxtBiddingConstraintType, WxtBizCode, WxtUtils} from "~/contentScripts/views/wxt/lib/wxtUtils";

const props = defineProps({
  value: {
    type: Boolean,
    default: false,
  },
  bizCode: {
    type: String as PropType<WxtBizCode>,
    default: WxtBizCode.关键字推广,
  },
  promotionScene: {
    type: String as PropType<WxtBiddingConstraintType>,
    default: WxtBiddingConstraintType.促进全店成交,
  },
  data: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  products: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  plans: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  showBottom: {
    type: Boolean,
    default: true,
  },
});
const emit = defineEmits([
  "update:value",
  "next",
  "prev",
]);
const getProductsData = () => {
  return props.data.filter((item: any) => item.key === 'choiceProduct')[0].value;
}
const products = computed(() => {
  return props.products.length>0?props.products:getProductsData();
});
const getPlansData = () => {
  return props.data.filter((item: any) => item.key === 'choicePlan')[0].value;
}
const plans = computed(() => {
  return props.plans.length>0?props.plans:getPlansData();
});
// 主Tabs
const tabs = reactive<any[]>([
  {
    title: '人群榜单',
    key: 'crowd',
    component: null,
    children: [
      {
        title: '转化效果榜单',
        key: 'conversion',
        recSceneList: [
          FindRecommendCrowdRecScene.转化效果榜单
        ],
        component: FindRecommendCrowdPanel,
        value: [],
      },
      {
        title: '使用热度榜单',
        key: 'hot',
        recSceneList: [
          FindRecommendCrowdRecScene.使用热度榜单
        ],
        component: FindRecommendCrowdPanel,
        value: [],
      },
      {
        title: '热门场景榜单',
        component: CrowdTopicTemplatePanel,
        value: [],
      }
    ]
  },
  {
    title: '系统推荐人群',
    key: 'system',
    component: FindRecommendCrowdPanel,
    recSceneList: [
      FindRecommendCrowdRecScene.系统推荐人群
    ],
    value: [],
  },
  {
    title: '自定义人群',
    key: 'custom',
    component: CustomCrowd,
    value:[],
  },
]);

// const getWords = () => {
//   let words = props.data.filter((item: any) => item.key === 'addKeyword')[0].value;
//   // console.log(words);
// }
// watch(() => props.data, () => {
//   getWords();
// })
// getWords();
const dataSource = ref<any[]>([]);
watch(() => tabs, () => {
  let values: any[] = [];
  // 从tbas中获取value 如果有子tabs则获取子tabs的value
  tabs.forEach((item) => {
    if (item.children) {
      item.children.forEach((child: any) => {
        values.push(...child.value.map((it: CrowdLabelInterface) => {
          return {
            typeName: child.title,
            bizCode: props.bizCode,
            crowd: {
              crowdName: it.optionList.map((i) => i.optionName).join(','),
              label: it,
              targetType: it.targetType,
            },
            mx_crowdId: it.targetType + '_' + it.labelId + '_' + it.optionList[0].optionValue,
            price: { // 溢价
              discount: dataSource.value.find((i) => i.mx_crowdId === it.targetType + '_' + it.labelId + '_' + it.optionList[0].optionValue)?.price.discount || 5,
            }
          };
        }));
      })
    } else {
      values.push(...item.value.map((it: CrowdLabelInterface) => {
        return {
          typeName: item.title,
          bizCode: props.bizCode,
          crowd: {
            crowdName: it.optionList.map((i) => i.optionName).join(','),
            label: it,
            targetType: it.targetType,
          },
          mx_crowdId: it.targetType + '_' + it.labelId + '_' + it.optionList[0].optionValue,
          price: { // 溢价
            discount: dataSource.value.find((i) => i.mx_crowdId === it.targetType + '_' + it.labelId + '_' + it.optionList[0].optionValue)?.price.discount || 5,
          }
        };
      }));
    }
  })
  dataSource.value = values.reverse();
}, {
  deep: true
})
watch(() => dataSource.value, () => {
  emit('update:value', dataSource.value.map((item) => {
    // 返回 移除 typeName字段 的数据 不影响原数据
    let {
      typeName,
      ...rest
    } = item;
    return rest;
  }));
})
const columns = [
  {
    title: '人群类型',
    dataIndex: 'typeName',
    width: 140,
  },
  {
    title: '人群名称',
    dataIndex: 'crowd.crowdName',
    key: 'crowd.crowdName',
  },
  {
    title: '溢价',
    dataIndex: 'price.discount',
    dataType: 'custom',
    slot: 'price',
    width: 120,
  },
  {
    title: '操作',
    dataType: 'custom',
    slot: 'action',
    width: 100,
  },
];
const selectedRows = ref<any[]>([]);
const remove = (row: any) => {
  let index = dataSource.value.findIndex((item) => item.mx_crowdId === row.mx_crowdId);
  dataSource.value.splice(index, 1);
}
const changeDiscount = (row: any, val: number) => {
  // 大于等于5 小于等于300
  if (val < 5 || val > 300) {
    message.error('溢价比例范围为5%~300%');
    return;
  }
  // 修改溢价比例 直接从dataSource中修改
  let index = dataSource.value.findIndex((item) => item.mx_crowdId === row.mx_crowdId);
  if (index === -1) return;
  dataSource.value[index].price.discount = val;
}
const visibleModifyPrice = ref<boolean>(false);
const priceDiscount = ref<number>(5);
const modifyPrice = () => {
  if (selectedRows.value.length === 0) {
    message.error('请选择要修改溢价的人群');
    return;
  }
  // 批量修改溢价
  selectedRows.value.forEach((row) => {
    let index = dataSource.value.findIndex((item) => item.mx_crowdId === row.mx_crowdId);
    if (index === -1) return;
    dataSource.value[index].price.discount = priceDiscount.value;
  })
  visibleModifyPrice.value = false;
  message.success('批量修改溢价成功');
}
const removeCrowd = () => {
  // 删除人群
  if (selectedRows.value.length === 0) {
    message.error('请选择要删除的人群');
    return;
  }
  selectedRows.value.forEach((row) => {
    let index = dataSource.value.findIndex((item) => item.mx_crowdId === row.mx_crowdId);
    if (index === -1) return;
    dataSource.value.splice(index, 1);
  })
  message.success('删除人群成功');
}
const activeKey = ref('custom');
</script>

<template>
  <a-row :gutter="10" style="height: 690px;">
    <a-col flex="1" style="height: 100%;overflow-y: auto;">
      <a-tabs type="card" v-model:active-key="activeKey">
        <a-tab-pane v-for="item in tabs" :key="item.key" :tab="item.title" forceRender>
          <a-tabs size="small" style="margin-top: -15px;">
            <a-tab-pane :key="child.key" :tab="child.title" v-if="typeof item.children!=='undefined'"
                        v-for="child in item.children"
                        forceRender
            >
              <component :is="child.component" v-if="child.component" :recSceneList="child.recSceneList||[]"
                         :bizCode="bizCode" :materialIdList="products.map((it)=>it.itemId||it.material.materialId)" v-model:value="child.value"
                         :campaignId="plans[0].campaignId"
              />
            </a-tab-pane>
          </a-tabs>
          <component :is="item.component" v-if="item.component" :bizCode="bizCode" v-model:value="item.value"
                     :materialIdList="products.map((it)=>it.itemId||it.material.materialId)" :recSceneList="item.recSceneList||[]"
                     :campaignId="plans[0].campaignId"
          />
        </a-tab-pane>
      </a-tabs>
    </a-col>
    <a-col flex="1" style="overflow: hidden;">
      <base-table :scroll="{
        y:600
      }" title="添加人群" :data-source="dataSource" :columns="columns" row-key="mx_crowdId" selection
                  v-model:selected-rows="selectedRows"
      >
        <template #header>
          <a-row style="padding:0 10px;">
            <a-col flex="1" style="color: #666;">
              待添加人群 {{ dataSource.length }} 个
            </a-col>
            <a-col>
              <a-space>
                <!--                // 批量修改溢价 使用Popover弹出修改框-->
                <a-popover placement="left" v-model:open="visibleModifyPrice" trigger="click">
                  <template #title>
                    <a-space>
                      <span>批量修改溢价</span>
                    </a-space>
                  </template>
                  <template #content>
                    <a-row type="flex">
                      <a-col flex="1">
                        溢价比例：
                      </a-col>
                      <a-col>
                        <a-input-number size="small" v-model:value="priceDiscount" :min="5" :max="300" :step="5"
                                        style="width: 100px;">
                          <template #addonAfter>%</template>
                        </a-input-number>
                      </a-col>
                    </a-row>
                    <a-divider style="margin: 10px 0;"/>
                    <!--                      // 确认和取消 居中显示-->
                    <a-row justify="end">
                      <a-space>
                        <a-button type="primary" size="small" @click="modifyPrice">确认</a-button>
                        <a-button size="small" @click="visibleModifyPrice=false">取消</a-button>
                      </a-space>
                    </a-row>
                  </template>
                  <a-button type="primary" size="small">批量修改溢价</a-button>
                </a-popover>
                <a-button type="primary" size="small" @click="removeCrowd">删除人群</a-button>
              </a-space>
            </a-col>
          </a-row>
        </template>
        <template #action="row">
          <a-button type="primary" danger size="small" @click="()=>{remove(row)}">删除</a-button>
        </template>
        <template #price="row">
          <!--          // 修改溢价比例-->
          <a-input-number :value="row.price.discount" size="small" @change="(val)=>changeDiscount(row,val)" :min="5"
                          :max="300" :step="5" style="width: 100px;"
          >
            <template #addonAfter>%</template>
          </a-input-number>
        </template>
      </base-table>
    </a-col>
  </a-row>
  <a-divider style="margin-top: 10px;" v-if="showBottom"/>
  <a-row type="flex" v-if="showBottom">
    <a-col flex="1">
    </a-col>
    <a-col>
      <a-space>
        <a-button @click="emit('prev',[])">上一步</a-button>
        <a-button type="primary" @click="()=> emit('next',[])">下一步</a-button>
      </a-space>
    </a-col>
    <a-col flex="1">
    </a-col>
  </a-row>
</template>

<style scoped>

</style>
